package moe.oil.db.service;

import lombok.Setter;
import moe.oil.db.entity.Professional;
import moe.oil.db.repo.ProfessionalRepo;
import moe.oil.dto.ProfessionalDTO;
import moe.oil.exception.comments.CommentsIdNullException;
import moe.oil.exception.professional.ProfessionalIdNullException;
import moe.oil.exception.professional.ProfessionalNameNullException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * author: 紫月
 * Date: 2022/04/19 17:01
 * Description:
 *
 * @author - -
 */
@Service
@Setter(onMethod_ = @Autowired)
public class ProfessionalService {
    private ProfessionalRepo professionalRepo;

    // 根据id查询专业
    public Optional<ProfessionalDTO> selectProfessionalId(Long id) {
        return Optional.of(professionalRepo.findByProfessionalId(id).orElseThrow(() -> new ProfessionalIdNullException(id)).convert());
    }

    // 根据专业名查询
    public Optional<ProfessionalDTO> selectProfessionalName(String professionalName) {
        return Optional.of(professionalRepo.findByName(professionalName).orElseThrow(() -> new ProfessionalNameNullException(professionalName)).convert());
    }

    // 查询全部专业
    public List<ProfessionalDTO> selectProfessionalAll(PageRequest pageRequest) {
        return professionalRepo.findAll(pageRequest).stream().map(Professional::convert).collect(java.util.stream.Collectors.toList());
    }

    // 添加专业
    public Optional<ProfessionalDTO> saveProfessional(ProfessionalDTO professionalDTO) {
        return Optional.of(professionalRepo.save(new Professional(professionalDTO)).convert());
    }

    // 根据ID删除专业
    public int deleteProfessionalId(Long id) {
        var delete = professionalRepo.deleteByProfessionalId(id);
        if (delete != 0) {
            return delete;
        } else {
            throw new ProfessionalIdNullException(id);
        }
    }

    // 修改
    public Optional<ProfessionalDTO> updateProfessional(ProfessionalDTO professionalDTO) {
        if (professionalDTO.getProfessionalId() != null && professionalDTO.getProfessionalId() != 0) {
            return Optional.of(professionalRepo.save(new Professional(professionalDTO)).convert());
        } else {
            throw new CommentsIdNullException(professionalDTO.getProfessionalId());
        }
    }
}
